import { FormGroup } from '@angular/forms';
import { getJson } from '../../../utils/utils';
import { AfterViewInit, Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { map } from 'rxjs/operators';
import { ApesDrawerRef } from '@shared/apes/drawer/apes-drawer-ref';
import { Observable } from 'rxjs/index';
import { ApiService } from '@core/services/http/api.service';
import { SubjectService } from '@core/services/events/subject.service';
import { FormlyFormOptions } from '@ngx-formly/core';
import { Events } from '@core/services/events/Events';

@Component({
  selector: 'apes-drawer-custom-grid-component',
  template: `
    <form [formGroup]="form">
      <form apes-form>
        <div>
          <apes-spin *ngIf="isLoading" apesSimple [apesSize]="'large'" class="drawer-spin"></apes-spin>
        </div>
        <apes-container [datas]="formMetadata" [form]="form" [model]="model" [options]="options"
                        [apesPrefixCls]="'apes-drawer-container'" [isDrawer]="true">
        </apes-container>
      </form>
    </form>

  `,
  styles: [`
    .ui-scrollpanel-bar {
      display: none;
    }
    .drawer-spin {
      width: 0;
      right: 0;
      height: 0;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      margin: auto;
    }

    apes-drawer-custom-grid-component > apes-drawer-body {
      padding: 0px ! important;
    }
  `],
  encapsulation: ViewEncapsulation.None,
})
export class ApesDrawerCustomGridComponent implements OnInit, AfterViewInit {
  @Input() formId = '';
  @Input() api = '';
  form: any;
  model: any;
  formMetadata = [];
  ctx = {};

  private _current = 0;
  private _pages = 0;

  /**订阅主题**/
  subjects = {};
  options: FormlyFormOptions = {};

  isLoading: boolean = false;

  constructor(private drawerRef: ApesDrawerRef<string>, private apiService: ApiService, private subject: SubjectService,
              protected events: Events) {
  }

  ngOnInit() {
    this.form = new FormGroup({});
    this.model = {};
    this.ctx['model'] = this.model;
    this.ctx['subjects'] = this.subjects;
    this.options.formState = this.ctx;
    this.subject.publish(this.ctx, 'drawer', this.model);
    this.events.subscribe('drawer', () => {
      this.events.unsubscribe('drawer');
      this.drawerRef.close(this.formId);
    });
  }

  ngAfterViewInit(): void {
    const data = this.drawerRef['apesContentParams'].data;
    this.ctx['condition'] = data;
    if (this.api == '') {
      this.getFormMetadata(this.formId);
    } else {
      setTimeout(()=>{
        this.isLoading = true;
        this.apiService.post(this.api, data).pipe(map(
          (body) => {
            if (body) {
              this.model = body;
              this.ctx['model'] = this.model;
              this.isLoading = false;
              this.subject.publish(this.ctx, 'drawer', this.model);
              this.getFormMetadata(this.formId);
            }
          })).subscribe();
      },100);
    }

  }

  close(): void {
    this.drawerRef.close(this.formId);
  }

  /**
   * 功能：获取表单元数据
   */
  private getFormMetadata(formId) {

    this.getFormMetadataApi(formId).pipe().subscribe((body) => {
      // let metadata = body;
      let metadata = body.sheet;
      // this.extFormMetadata(metadata);
      this.formMetadata = this.formMetadata.concat(metadata);
    });

  }

  private getFormMetadataApi(formId: string): Observable<any> {
    return this.apiService.post('form.get', { 'body': getJson({ id: formId }) }).pipe(map(
      (body) => {
        if (body) {
          return body;
        }
      }));
  }

  submit() {
    alert(JSON.stringify(this.model));
  }
}
